#!/usr/bin/env python
#coding=utf-8

import time, json
from hashlib import sha256

from flask import Blueprint, g, request, redirect, url_for, render_template, make_response, session, current_app

from codingabc.database import db
from codingabc.helpers import log_debug, log_info, toint, randomstr, get_count

from app.helpers.date_time import current_timestamp
from app.services.user import AccountSmsService
from app.models.user import User, UserPassword, UserCheckCode, UserAdmin
from app.models.role import Role
from app.services.code import generate_verification_code
from app.services.yunpian import YunPian
from app.helpers.common import menu
from app.services.get_data import role_name, user_role_id_list, get_role_list

index = Blueprint('index', __name__)

@index.route('/')
def welcome():
    """ 首页 """

    uid = toint(session.get('uid', 0))
    if uid <= 0:
        return redirect(url_for('index.signin'))

    return redirect(url_for('user.index'))


@index.route('/signin', methods=['GET', 'POST'])
def signin():
    """ 登陆 """

    if request.method == 'GET':
        args = request.args
        mobile   = args.get('mobile', '').strip('')
        password = args.get('password', '').strip('')

        if mobile and password:
            # 修改密码成功，直接登录
            return login_check(mobile,password)

        return render_template('signin.html', f={}, errormsg={})

    form = request.form
    mobile      = form.get('mobile', '').strip()
    password    = form.get('password', '').strip()
    code        = form.get('code', '').strip()
    code        = u'%s'% code
    if mobile and password and code:
        return login_check(mobile, password, form, code)

    log_info('### mobile:%s, password:%s, code:%s'%(mobile, password, code))
    return render_template('signin.html', f={}, errormsg={})


def login_check(mobile='',password='', form={}, code='',errmsg=None):
    """ 登陆检查 """

    if not mobile:
        return render_template('signin.html', f=form, errmsg=u'手机号不能为空')

    if not password:
        return render_template('signin.html', f=form, errmsg=u'密码不能为空')

    if len(code) != 6:
        return render_template('signin.html', f=form, errmsg=u'输入6位验证码')

    code_text = session.get('code_text', '')
    if code_text.upper() != code.upper() and current_app.config['SQLALCHEMY_BINDS']['huiwang'] == current_app.config['DB_CONNECT_STRING']:
        return render_template('signin.html', f={'mobile':mobile}, errmsg=u'输入的验证码不正确, 请重新获取')

    me = User.query.filter(User.mobile == mobile).first()
    if me is None:
        return render_template('signin.html', f=form, errmsg=u'用户不存在')

    up = UserPassword.query.filter(UserPassword.uid == me.uid).filter(UserPassword.type == 1).first()
    if up is None:
        return render_template('signin.html', f=form, errmsg=u'还没有设置密码')

    sha256_password = sha256(password).hexdigest()
    sha256_password = sha256(sha256_password+up.salt).hexdigest()
    if sha256_password != up.password:
        return render_template('signin.html', f=form, errmsg=u'密码错误')

    ua = UserAdmin.query.filter(UserAdmin.uid == me.uid).\
            filter(UserAdmin.role_id > 0).first()

    if ua is None:
        return render_template('signin.html', f=form, errmsg=u'您没有权限登录系统，请联系可爱的管理员')

    role = Role.query.get(ua.role_id)
    if not role:
        return render_template('signin.html', f=form, errmsg=u'获取角色信息失败，请联系可爱的管理员')

    # if role.role_name == u'老师':
    #     return render_template('signin.html', f=form, errmsg=u'老师没有权限登录')

    role_id_list = user_role_id_list(me.uid)
    role_id_list.remove(ua.role_id)
    ROLE_NAME = role_name()

    session['admin_id']     = me.uid
    session['admin_name']   = me.mobile
    session['uid']          = me.uid
    session['mobile']       = mobile
    session['nickname']     = me.nickname
    session['cs_id']        = me.cs_id
    session['role_id']      = ua.role_id
    session['role_temp_list'] = get_role_list(role_id_list) if len(role_id_list) > 0 else []
    session['role_name']    = ROLE_NAME.get(ua.role_id, '')
    session['menu']         = menu(ua.role_id)

    if not session['menu'] and ua.role_id == 1:
        return redirect(url_for('sys.menu_list'))
    else:
        return redirect(url_for('user.index'))


@index.route('/signout')
def signout():
    """ 登出 """

    session.clear()

    return redirect('/')


@index.route('/change/password')
def change_password():
    """ 修改密码 """

    args = request.args
    old_password = args.get('old_password', '')
    password1    = args.get('password1', '')
    password2    = args.get('password2', '')
    uid          = session.get('uid')

    if uid <= 0:
        return u'参数出错'

    up = UserPassword.query.filter(UserPassword.uid == uid).first()

    #判断旧密码是否正确
    sha256_old_password = sha256(old_password).hexdigest()
    old_password = sha256(sha256_old_password+up.salt).hexdigest()

    if old_password != up.password:
        return 'error_password'

    salt         = randomstr(32)
    password1    = sha256(password1).hexdigest()
    new_password = sha256(password1+salt).hexdigest()

    up.salt     = salt
    up.password = new_password
    db.session.commit()

    return 'ok'


@index.route('/forget/password')
def forget_password():
    """忘记密码"""

    args     = request.args
    mobile   = args.get('mobile', '')
    code     = args.get('code', '')
    password = args.get('password1', '')

    current_time = current_timestamp()
    ucc = UserCheckCode.query.filter(UserCheckCode.mobile == mobile).\
                filter(UserCheckCode.check_code == code).\
                filter(UserCheckCode.check_type == 2).\
                order_by(UserCheckCode.ucc_id.desc()).first()
    if ucc is None:
        return u'验证码错误'

    if ucc.expire_time < current_time:
        return u'验证码已经过期，请重新获取'

    user = db.session.query(User.uid, User.mobile).filter(User.mobile == mobile).first()
    if user is None:
        return u'{mobile}帐号不存在'.format(mobile=mobile)

    up          = UserPassword.query.filter(UserPassword.uid == user.uid).first()
    password    = sha256(password).hexdigest()
    password    = sha256(password+up.salt).hexdigest()
    up.password = password
    db.session.commit()

    return u'ok'


@index.route('/getcode', methods=['POST'])
def getcode():
    """获取验证码"""

    form = request.form
    mobile     = form.get('mobile', '').strip()
    check_type = toint(form.get('check_type', 0))

    ass = AccountSmsService(mobile, check_type)
    msg = ''
    if not ass.check_mobile():
        msg = ass.msg

    if not ass.check_code_type(is_create=True):
        msg = ass.msg

    if ass.is_repeat():
        msg = ass.msg

    if msg:
        return msg

    if ass.sms_day_limit_surplus() <= 0:
        return u'一天之内只能获取%d次验证码，请明天再来获取' % ass.SMS_DAY_LIMIT

    code    = ass.create_code()
    content = ass.create_content(code)

    interval_minute = ass.send(code, content)
    if not interval_minute:
        return u'发送验证码失败'

    return 'ok'


@index.route('/get_verify_code')
def get_verify_code():
    """ 获取验证码 """

    code_img, code_text = generate_verification_code()
    session['code_text'] = code_text
    response = make_response(code_img)
    response.headers['Content-Type'] = 'image/jpeg'
    return response
